package com.zy.xuanwo.view;

import android.content.Context;
import android.os.Handler;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.zy.xuanwo.R;

/**
 * remarks:
 * Created by ChowYvlChen on 2016/7/5  11:05
 */
public class CustomToast {


    private static Toast mToast;

    /**
     * Toast时间
     */
    public static int TOAST_TIME = 3000;

    private static Handler mHandler = new Handler();

    private static Runnable r = new Runnable() {

        public void run() {
            mToast.cancel();
        }
    };

    public static void showToast(Context mContext, String text, int duration) {
        LayoutInflater inflater = LayoutInflater.from(mContext);
        View view = inflater.inflate(R.layout.toast_common, null);
        TextView txt = (TextView) view.findViewById(R.id.common_toast_tv);
        txt.setText(text);
        mHandler.removeCallbacks(r);
        if (mToast != null) {
            mToast.setView(view);
        } else {
            mToast = new Toast(mContext);
            mToast.setGravity(Gravity.CENTER, 0, 120);
            mToast.setDuration(Toast.LENGTH_LONG);
            mToast.setView(view);
        }

        mHandler.postDelayed(r, duration);

        mToast.show();
    }

    public static void showToast(Context mContext, int resId, int duration) {
        showToast(mContext, mContext.getResources().getString(resId), duration);
    }

    public static void showToast(Context mContext, String content) {
        if (mContext != null) {
            showToast(mContext.getApplicationContext(), content, TOAST_TIME);
        }
    }

    public static void showToast(Context mContext, int resId) {
        showToast(mContext.getApplicationContext(), resId, TOAST_TIME);
    }

    public static Toast getToast(Context mContext, String text) {
        LayoutInflater inflater = LayoutInflater.from(mContext);
        View view = inflater.inflate(R.layout.toast_common, null);
        TextView txt = (TextView) view.findViewById(R.id.common_toast_tv);
        if (mToast != null) {
            mToast.setView(view);
        } else {
            mToast = new Toast(mContext);
            mToast.setGravity(Gravity.CENTER, 0, 120);
            mToast.setDuration(Toast.LENGTH_LONG);
            mToast.setView(view);
        }
        return mToast;
    }

    public static void cancel() {
        mToast.cancel();
    }
}
